import base64
import json
from time import sleep

from PySide6.QtCore import QObject, Signal

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models

class InvoiceIdentify(QObject):
    finished_signal = Signal(int)      # 提前结束的信号
    rel_tip_signal = Signal(str, str)

    def __init__(self, file, secret_id, secret_key):
        super().__init__()
        self.file = file
        self.secret_id = secret_id
        self.secret_key = secret_key
        self.attempts_num = 0
    def f1(self):
        '''
        通用票据识别（高级版），5次/秒
        https://cloud.tencent.com/document/product/866/90802
        '''
        file_type = self.file.split('.')[-1]
        if file_type not in ('jpg', 'jpeg', 'png', 'pdf'):
            self.rel_tip_signal.emit(f'文件 {self.file} 格式不支持，跳过', 'yellow')
            return
        try:
            if self.attempts_num >= 4:
                self.rel_tip_signal.emit(f'{self.file} 失败三次，已跳过', 'yellow')
                return
            self.attempts_num += 1

            cred = credential.Credential(self.secret_id, self.secret_key)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "ocr.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile

            client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)

            req = models.RecognizeGeneralInvoiceRequest()
            with open(self.file, 'rb') as file:
                file_base64 = base64.b64encode(file.read()).decode('utf-8')
            params = {
                "ImageBase64": file_base64
            }
            req.from_json_string(json.dumps(params))

            resp = client.RecognizeGeneralInvoice(req)
            return resp
        except TencentCloudSDKException as err:
            self.rel_tip_signal.emit(f'{self.file} 失败，2秒后重试，错误信息：{err}', 'yellow')
            sleep(2)
            self.f1()